//
//  LoginViewController.m
//  SuperMedical
//
//  Created by 赵隆杰 on 2018/7/28.
//  Copyright © 2018年 赵隆杰. All rights reserved.
//

#import "LoginViewController.h"
#import "ForgetViewController.h"
#import "RegisterViewController.h"
#import "LoginApi.h"
#import "UserInfoApi.h"
#import <AuthenticationServices/AuthenticationServices.h>

@interface LoginViewController ()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
@property (weak, nonatomic) IBOutlet UIView *inputView;
@property (weak, nonatomic) IBOutlet UIImageView *moblieImage;
@property (weak, nonatomic) IBOutlet UITextField *moblieField;
@property (weak, nonatomic) IBOutlet UIImageView *passwordImage;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation LoginViewController

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
//}
//
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:NO];
//}

- (void)dealloc {
    if (@available(iOS 13.0, *)) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:ASAuthorizationAppleIDProviderCredentialRevokedNotification object:nil];
    } else {
        // Fallback on earlier versions
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.naviView.hidden = YES;
    // 注册通知
    if (@available(iOS 13.0, *)) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSignInWithAppleStateChanged:) name:ASAuthorizationAppleIDProviderCredentialRevokedNotification object:nil];
    } else {
        // Fallback on earlier versions
    }
    
    [self configView];
    
    UILabel *argeeLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, SL_WINDOW_HEIGHT - UIDevice.vg_safeDistanceBottom - 50, 90, 40)];
    argeeLabel.font = [UIFont systemFontOfSize:12];
    argeeLabel.text = @"登录即代表同意";
    argeeLabel.textColor = kColor333333;
    [self.view addSubview:argeeLabel];
    
    UIButton *argeeBtn1 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(argeeLabel.frame), argeeLabel.frame.origin.y, 80, 40)];
    argeeBtn1.tag = 1;
    argeeBtn1.titleLabel.font = [UIFont systemFontOfSize:12];
    [argeeBtn1 setTitle:@"《隐私协议》" forState:UIControlStateNormal];
    if (@available(iOS 13.0, *)) {
        [argeeBtn1 setTitleColor:[UIColor linkColor] forState:UIControlStateNormal];
    } else {
        [argeeBtn1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    }
    [argeeBtn1 addTarget:self action:@selector(argeeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:argeeBtn1];
    
    UIButton *argeeBtn2 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(argeeBtn1.frame), argeeLabel.frame.origin.y, 80, 40)];
    argeeBtn2.tag = 2;
    argeeBtn2.titleLabel.font = [UIFont systemFontOfSize:12];
    [argeeBtn2 setTitle:@"《用户协议》" forState:UIControlStateNormal];
    if (@available(iOS 13.0, *)) {
        [argeeBtn2 setTitleColor:[UIColor linkColor] forState:UIControlStateNormal];
    } else {
        [argeeBtn2 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    }
    [argeeBtn2 addTarget:self action:@selector(argeeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:argeeBtn2];
    
}

- (void)configView
{
    self.loginBtn.layer.cornerRadius = self.loginBtn.height/2;
    self.loginBtn.layer.masksToBounds = YES;
    
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDButton *appleIDBtn = [ASAuthorizationAppleIDButton buttonWithType:ASAuthorizationAppleIDButtonTypeDefault style:ASAuthorizationAppleIDButtonStyleWhiteOutline];
        
//        appleIDBtn.frame = CGRectMake(40, CGRectGetMaxY(self.loginBtn.frame) + 10, SL_WINDOW_WIDTH - 80, self.loginBtn.frame.size.height);
        appleIDBtn.cornerRadius = 25;
        [appleIDBtn addTarget:self action:@selector(didAppleIDBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:appleIDBtn];
        [appleIDBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(40);
            make.top.equalTo(self.loginBtn.mas_bottom).offset(10);
            make.width.height.equalTo(self.loginBtn);
        }];
        
    } else {
        // Fallback on earlier versions
    }
}

- (IBAction)loginClick:(id)sender {
    NSLog(@"登录");
    
    [self.view endEditing:YES];
    if ([self.moblieField.text isEqualToString:@""]) {
        [self.view makeToast:@"请输入账号" duration:2.0 position:CSToastPositionCenter];
        return;
    }
//    else if (![self.moblieField.text validateMobileWithToast]) {
//        return;
//    }
    if ([self.passwordField.text isEqualToString:@""]) {
        [self.view makeToast:@"请输入密码" duration:2.0 position:CSToastPositionCenter];
        return;
    }
    //登录接口不传token和uid
    
    LoginApi *api = [[LoginApi alloc] initWithUserName:self.moblieField.text passWord:self.passwordField.text];
    api.hideHUD = YES;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"登录中...";
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [hud hideAnimated:YES];
        if (api.success) {
            //先保存token uid
            NSString *token = (NSString *)api.res;
            [LocalData saveToken:token];
            [self userInfoRequest];
            
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [hud hideAnimated:YES];
    }];
}

- (void)userInfoRequest
{
    UserInfoApi *api = [[UserInfoApi alloc] initWithToken:[LocalData getToken]];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (api.success) {
            [LocalData saveUserInfoDic:api.res];
            self.loginCompleteBlock(YES);
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}
- (IBAction)forgetClick:(id)sender {
    NSLog(@"忘记密码");
    ForgetViewController *vc = [[ForgetViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)registerClick:(id)sender {
    NSLog(@"注册");
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)cancelAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)argeeBtnClick:(UIButton *)button
{
    if (button.tag == 1) {
        //隐私协议
        [[AppLogic sharedInstance] pushToWebViewVC:@"隐私协议" url:@"https://www.7pa.com/yhhnqply.html"];
    } else {
        //用户协议
        [[AppLogic sharedInstance] pushToWebViewVC:@"用户协议" url:@"https://www.7pa.com/yhhnqply.html"];
    }
}

- (void)didAppleIDBtnClicked
{
    if (@available(iOS 13.0, *)) {
        
        ASAuthorizationAppleIDProvider * appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest * authAppleIDRequest = [appleIDProvider createRequest];
        ASAuthorizationController * authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[authAppleIDRequest]];
        authorizationController.delegate = self;
        authorizationController.presentationContextProvider = self;
        [authorizationController performRequests];
        
    } else {
        // 处理不支持系统版本
        NSLog(@"系统不支持Apple登录");
    }
    
}

#pragma mark- ASAuthorizationControllerDelegate
// 授权成功
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    
    ASAuthorizationAppleIDCredential * credential = (ASAuthorizationAppleIDCredential*)authorization.credential;
    
    // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
    NSString * userID = credential.user;
    
    // 苹果用户信息 如果授权过，可能无法再次获取该信息
    NSPersonNameComponents * fullName = credential.fullName;
    NSString * email = credential.email;
    
    // 服务器验证需要使用的参数
    NSString * authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
    NSString * identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
    
    // 用于判断当前登录的苹果账号是否是一个真实用户，取值有：unsupported、unknown、likelyReal
    ASUserDetectionStatus realUserStatus = credential.realUserStatus;
    
    NSLog(@"userID: %@", userID);
    NSLog(@"fullName: %@", fullName);
    NSLog(@"email: %@", email);
    NSLog(@"authorizationCode: %@", authorizationCode);
    NSLog(@"identityToken: %@", identityToken);
    NSLog(@"realUserStatus: %@", @(realUserStatus));

    LoginApi *api = [[LoginApi alloc] initWithAppleId:userID];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"登录中...";
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [hud hideAnimated:YES];
        if (api.success) {
            //先保存token uid
            NSString *token = (NSString *)api.res;
            [LocalData saveToken:token];
            [self userInfoRequest];
            
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [hud hideAnimated:YES];
    }];
}

// 授权失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    
    NSString *errorMsg = nil;
        
        switch (error.code) {
            case ASAuthorizationErrorCanceled:
                errorMsg = @"用户取消了授权请求";
                break;
            case ASAuthorizationErrorFailed:
                errorMsg = @"授权请求失败";
                break;
            case ASAuthorizationErrorInvalidResponse:
                errorMsg = @"授权请求响应无效";
                break;
            case ASAuthorizationErrorNotHandled:
                errorMsg = @"未能处理授权请求";
                break;
            case ASAuthorizationErrorUnknown:
                errorMsg = @"授权请求失败未知原因";
                break;
        }
        NSLog(@"%@", errorMsg);
}

#pragma mark- ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)) {
    return self.view.window;
}

#pragma mark- apple授权状态 更改通知
- (void)handleSignInWithAppleStateChanged:(NSNotification *)notification
{
    NSLog(@"%@", notification.userInfo);
}

@end
